package org.example.common.codec;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @title
 * @time 2025/6/17 0:21
 */
@Component
@Slf4j
public class InvocationEncoder extends MessageToByteEncoder<Invocation> {
    @Override
    protected void encode(ChannelHandlerContext ctx, Invocation invocation, ByteBuf out) throws Exception {
        // <2.1> 将 Invocation 转换成 byte[] 数组
        String jsonString = JSONObject.toJSONString(invocation);
        byte[] content = jsonString.getBytes(StandardCharsets.UTF_8);
        // <2.2> 写入 length
        out.writeInt(content.length);
        // <2.3> 写入内容
        out.writeBytes(content);
        log.info("[encode][连接({})] 编码了一条消息{}", ctx.channel().id(), jsonString);

    }
}
